<!--合约平仓操作页-->
<template>
  <div class="vt-funlvue">

    <!--操作按钮-买卖-->
    <div class="row">
      <div :class="['action-but', getUpDownBr(!actionType, false)]" 
      @click="sellClick">
        <text :class="['font32', getUpDownFont(!actionType, false)]">{{T("平多")}}</text>
      </div>
      <div class="width10"></div>
      <div :class="['action-but', getUpDownBr(actionType, true)]"  
      @click="buyClick">
        <text :class="['font32', getUpDownFont(actionType, true)]">{{T("平空")}}</text>
      </div>
    </div>

    <!--功能类型-->
    <div class='types'>
      <div class="row acenter" @click="functionClick">
        <text class="font28 text1 all">{{T(type)}}</text>
        <LImage class="img-arrow-down" :src="Config.img('trading_triangle_white.png')"></LImage>
      </div>
    </div>

    <!--价格-->
    <template v-if="type=='限价委托'">
      <VTInput class="frame" v-model="price" changeValue="0.1"
      :selectColor="getUpDownBr(true, actionType)" :placeholder="T('价格')"
      @change="priceChange"  />
      <div class="frame-tipe"></div>
    </template>
    <template v-else>
      <div class="market-price bg2"><text class="font28 text2 fall">{{T('以当前最优价格交易')}}</text></div>
      <div class="frame-tipe"></div>
    </template>

    <!--数量-->
    <VTInput class="frame" v-model="num" :unit="pair.counterCoin"
    :selectColor="getUpDownBr(true, actionType)" :placeholder="T('数量')"
    @change="numChange"  />
    <div class="frame-tipe"><text class="font24 text2">{{T('持仓')+' '+available+' '+pair.counterCoin}}</text></div> 
    <div class="frame-tipe"></div>
    <WeexSlideBar class="slide" ref='WeexSlideBar' :color="getUpDownFont(true, actionType)" />

    <!--操作-OK-->
    <div v-if="api" :class="['but-action-ok', Config.upDownBg(actionType)]" @click="okClick">
      <text class="font32 text1" v-if="!Config.isLogin">{{T('登录')}}</text>
      <text class="font32 text1" v-else-if="!api.apiId">{{T('录入API')}}</text>
      <text class="font32 text1" v-else-if="actionType">{{T('买入')+'('+T('平空')+')'}}</text>
      <text class="font32 text1" v-else>{{T('卖出')+'('+T('平多')+')'}}</text>
    </div>
  </div>
</template>


<script>
import jconfig from "@/_js/config"
import jmath from "@/_js/math"
import jmodal from "@/_js/modal"
import jnavigator from "@/_js/navigator"
import jhttps from "@/_js/https"

import jtrading from "./trading"

const weexFunction = weex.requireModule("WeexFunction")
const WeexTrading = weex.requireModule("WeexTrading")
const globalEvent = weex.requireModule('globalEvent');


import I18N from "@/_i18n/i18n";
var T = I18N.t;

import VTInput from './VTInput.vue'
export default {
  components: {
    VTInput
  },

  props:{
    api: Object, //api
    pair: Object, //交易对
    depthCout: { //深度数量
      type: Number,
      default: 8,
    }
  },

  watch: {
    api(val, oldVal) {
      if (val.apiId != oldVal.apiId) {
        jtrading.delectApiRsaStr(true);
        this.initChi();
      } else {
        this.initData(false);
      }
    },
    pair(val, oldVal) {
      if (val.counterCoin != oldVal.counterCoin) {
        this.initChi();
      } else {
        this.initData(false);
      }
    }
  },

  data() {
    return {
      T:T,
      Config:jconfig,
      
      publicKey:'', //加密秘钥
      
      actionType:false, //操作：true买入 false卖出

      //委托类型
      types:['限价委托', '市价委托'],
      typex:{'限价委托':'limit', '市价委托':'market'},
      type: '限价委托',

      price: '', //价格
      available:'0', //可平仓余额
      chiDuo:'0', //持多
      chiKong:'0', //持空
      dongjied:{}, //冻结

      num:'', //数量
      maxNum:'0', //可下单最大数量
    };
  },

  mounted() {
    jconfig.init(()=>{
      this.initChi();
      this.viewappear();
    }, [jconfig.OPT_UP_DOWN]);

    //获取在持仓页面点击平仓的方向参数
    weexFunction.getConfig('trading_contract_actiontype', (value)=>{
      if (!value) return;
      this.actionType = value!='LONG';
      this.initChi(false);
      weexFunction.setConfig('trading_contract_actiontype', '');
    });
  },
  
  computed: {
  },

  methods: {
    
    /************************************************* 通信*/
    //完全显示
    viewappear() {
      //滑条改变触发
      globalEvent.addEventListener("slideChange",(e)=>{
        this.slideChange(e.ratio);
      });
    },

    //完全隐藏
    viewdisappear() {
      globalEvent.removeEventListener("slideChange")
    },

    /********************************************** 初始化*/
    //初始化持仓
    initChi(isDelect=true, hud=true) {
      if(!this.api.apiId) {

        this.chiDuo = '0';
        this.chiKong = '0';
        this.initData(isDelect);
        return;
      }

      hud && jmodal.showLoad();
      jtrading.gtApiRsaStr(this.api, hud, true, (rsa)=>{
        this.httpsQueryPosition(rsa, isDelect, hud);
      });
    },
      
    /** 初始化数据
     * 1、清空数量
     * 2、初始化价格
     * 3、更新可用余额
     * 4、更新最大数量
     * 5、更新滑条
     */
    initData(isDelect=true, value) {
      
      if (isDelect) {
        this.num = '';
        this.price = this.pair.last;
      }

      this.upAvailable(value);
      this.upMaxNum();
      this.upSlideBar();
    },

    /********************************************** https*/
    //https查询持仓列表
    httpsQueryPosition(rsa, isDelect, hud){


      var param = {'apiData':rsa, 
                  'counterCoin':this.pair.counterCoin, 
                  'baseCoin':this.pair.baseCoin};
      jhttps.post("manual/queryPosition",param,true,(data)=>{

          if (data.status == 11505) { //服务器公钥过期
            jtrading.delectApiRsaStr(true);
            jtrading.gtApiRsaStr(this.api, true, false, (newrsa)=>{
              this.httpsQueryPosition(newrsa);
            });
            return;
          }

          hud && jmodal.hideLoad();
          if(data.status == 200){
            var datas = data.data.positionList;

            var chiDuo = '0';
            var chiKong = '0';
            datas.forEach((item)=>{
              item.positionSide == 'LONG' && (chiDuo = item.positionAmt);
              item.positionSide == 'SHORT' && (chiKong = item.positionAmt);
            })
            this.chiDuo = chiDuo;
            this.chiKong = chiKong;
            this.initData(isDelect);
          } else {
            hud &&jmodal.toast(data.msg);
          }
      });
    },

    //https下买卖单
    httpsPalceOrder(rsa){
      
      
      var amount = this.num;
      var param = {'side':this.actionType ? 'buy' : 'sell', //买卖单
                  'type':this.typex[this.type], //委托类型
                  'amount':amount, //下单数量
                  'offset':'0', //1开仓 0平仓

                  'apiData':rsa,  //API秘钥
                  'exchangeName':this.api.exchangeName, //交易所
                  'counterCoin':this.pair.counterCoin, //交易币
                  'baseCoin':this.pair.baseCoin, //本币所
      }; 

      //价格
      if(this.type == '限价委托') {
        param['price'] = this.price;
      }
      jhttps.postX("manual/palceOrder",param,true,(data)=>{

        if (data.status == 11505) { 
          jtrading.delectApiRsaStr(true);
          jtrading.gtApiRsaStr(this.api, true, true, (rsa)=>{
            this.httpsPalceOrder(rsa);
          });
          return;
        }

        jmodal.hideLoad();
        if(data.status == 200){
          jmodal.toast(T('委托成功'));

          if (this.type == '限价委托') {
            this.addDongjie(this.num);
          } else if (this.actionType) { //市价平空
            this.chiKong = jmath.jian(this.chiKong, this.num);
          } else { //市价平多
            this.chiDuo = jmath.jian(this.chiDuo, this.num);
          }
          this.initData(true);
          this.$emit('upOrder');
        } else{
          jmodal.toast(data.msg);
        }
      });
    },

    /********************************************** 其他*/
    //隐藏键盘
    hideKeyboard(){
      this.$refs.refTriggerPrice && this.$refs.refTriggerPrice.blur();
      this.$refs.refPrice && this.$refs.refPrice.blur();
      this.$refs.refNum && this.$refs.refNum.blur();
    },

    //获取涨跌边框色
    getUpDownBr(isUpDown, bol) {
      return isUpDown ? jconfig.upDownBr(bol, 'udRed-b1', 'udGreen-b1') : 'bk4';
    },

    //获取涨跌文字色
    getUpDownFont(isUpDown, bol) {
      return isUpDown ? jconfig.upDownFont(bol) : 'text2';
    },

    /********************************************** 数据更新*/
    //更新冻结
    upDongJie(dongjied) {
      this.dongjied = dongjied;
      this.initData(false);
    },
    
    //添加冻结
    addDongjie(value) {

      var side = this.actionType ? 'buy' : 'sell';
      var key = this.pair.counterCoin + side;
      var dongjie = this.dongjied[key];
      dongjie = dongjie ? dongjie : '0';
      dongjie = jmath.jia(dongjie, value);
      this.dongjied[key] = dongjie;
    },

    //更新余额
    upAvailable() {
      
      var side = this.actionType ? 'buy' : 'sell';
      var key = this.pair.counterCoin + side;
      var dongjie = this.dongjied[key];
      dongjie = dongjie ? dongjie : '0';

      var available = this.actionType ? this.chiKong : this.chiDuo;

      available = jmath.jian(available, dongjie);

      this.available = available < 0 ? '0' :available;
    },

    //更新最大数量
    upMaxNum(){
      this.maxNum = this.available;
    },

    //更新滑条
    upSlideBar(){
      
      if (!this.$refs.WeexSlideBar) {
        setTimeout(() => {
          this.upSlideBar();
        }, 100);
        return;
      }

      var rightStr = this.maxNum + this.pair.counterCoin;

      var color = jconfig.upDownBg(this.actionType, '#DB4564', '#00A986');
 
      var ratio = this.num.length ? jmath.chu(this.num, this.maxNum, 2, 2) : '0';
      ratio = ratio > 1 ? '1' : ratio;
      
      this.$refs.WeexSlideBar.upSlide({rightStr, color, ratio});
    },
  
    /********************************************** 数据联动*/
    /** 价格改变
     * 1、更新最大数
     * 2、更新滑条
     */
    priceChange(price){

      this.price = price;
      this.upMaxNum();
      this.upSlideBar();
    },

    /** 滑条改变
     * 1、计算数量
     */
    slideChange(ratio){
      if (this.maxNum == 0) {
        this.num = '';
        return;
      }

      var xs = jmath.getXiaoShuLength(this.pair.contractSize);
      this.num = jmath.cheng(this.maxNum, ratio, xs, 2);
    },
    
    /** 数量改变
     * 1、更新滑条
     */
    numChange(num){
      this.num = num;
      this.upSlideBar();
    },
    
    /********************************************** 点击*/
    //买入
    buyClick(){
      if (this.actionType) return;
      this.actionType = true;
      this.initData();
    },

    //卖出
    sellClick(){
      if (!this.actionType) return;
      this.actionType = false;
      this.initData();
    },

    //委托类型
    functionClick(){
      
      var types = [];
      var typed = {};
      for (let index = 0; index < this.types.length; index++) {
        var value = this.types[index];
        typed[T(value)] = index;
        types.push(T(value));
      }
      jmodal.actionSheet(types, T(this.type), (value)=>{
        if (T(this.type) == value) return;

        var index = typed[value];
        this.type = this.types[index];
        this.initData();
      });
    },

    //确定
    okClick(){
      
      if (jtrading.isFunlvue(this.api)) return;
      
      //价格未填写
      if ((this.type == '限价委托') && this.price.length == 0){
        jmodal.toast('请输入价格');
        return;
      }

      //价格不可为0
      if ((this.type == '限价委托') && this.price == 0){
        jmodal.toast('价格不可为0');
        return;
      }

      //数量未填写
      if (this.num.length == 0) {
        jmodal.toast('请输入数量');
        return;
      }
      
      //数量为0
      if (this.num == 0) {
        jmodal.toast('数量不可为0');
        return;
      }

      //可用余额不足
      if (Number(this.num) > Number(this.available)) {
        jmodal.toast('可用余额不足');
        return;
      }

      jmodal.showLoad();
      jtrading.gtApiRsaStr(this.api, true, true, (rsa)=>{
        this.httpsPalceOrder(rsa);
      });
    },
  }
};

</script>

<style src="@/_css/style.css" ></style>

<style scoped>

.vt-funlvue{
  flex: 1;
  flex-direction: column;
  margin-right: 40px;
}
.action-but{
  flex: 1;
  height:72px;
  justify-content: center;
  align-items: center;
  border-radius:2px;
  border-width:2px;
}
.types {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 50px;
}
.img-arrow-down {
  width:16px;
  height:12px;
  margin-left: 10px;
}
.market-price{
  height:80px;
  flex-direction: row;
  align-items: center;
  padding: 20px;
  margin-top: 60px;
}
.frame {
  height:80px;
  flex-direction: row;
  align-items: center;
  border-radius:2px;
  border-width: 2px;
  padding: 20px;
  margin-top: 60px;
}
.frame-tipe{
  flex-direction: column;
  justify-content: center;
  margin-top: 10px;
  height: 34px;
}
.slide{
  height:94px;
  margin-top: 60px;
  margin-bottom: 40px;
}

.but-action-ok{
  height:80px;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
</style>